<template>
    <div class="app-container">
        <!-- 健康提醒 -->
        <div class="health-reminder">
            <div class="section-title">健康提醒</div>
            <div class="reminder-content">
                <div class="reminder-item">
                    <i class="fas fa-calendar-check"></i>
                    <div class="reminder-info">
                        <div class="reminder-title">今日复诊提醒</div>
                        <div class="reminder-detail">心内科 李医生 下午 14:30</div>
                    </div>
                </div>
                <div class="reminder-item">
                    <i class="fas fa-file-medical-alt"></i>
                    <div class="reminder-info">
                        <div class="reminder-title">检查报告已出</div>
                        <div class="reminder-detail">血常规检查报告已完成</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 待支付提醒 -->
        <div class="payment-reminder" v-if="unpayList.length > 0">
            <div class="section-title payment-title" @click="togglePaymentDetails">
                <div>
                    缴费提醒
                </div>
                <div>
                    <span class="amount-badge">{{ unpayList.length }}</span>
                    <i class="fas fa-chevron-down toggle-icon" :class="{ 'rotated': showPaymentDetails }"></i>
                </div>

            </div>

            <div class="payment-details" v-show="showPaymentDetails">
                <div class="payment-list">
                    <div v-for="(item, index) in unpayList" :key="index" class="payment-item">
                        <div class="payment-info">
                            <div class="payment-title">订单 {{ item.orderNumber }}</div>
                            <div class="payment-meta">
                                <span class="doctor-name">医生：{{ item.patientName }}</span>
                                <span class="appointment-date">预约日期：{{ item.date }} {{ item.timeSolt }}</span>
                            </div>
                        </div>
                        <div>
                            <!-- 创建日期 {{ formatDate(visit.createTime) }} -->
                        </div>

                        <button class="pay-button" @click="handlePayment(item)">立即缴费</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 预约提醒
        <div class="health-reminder">
            <div class="section-title">预约提醒</div>
            <div class="reminder-content">
                <div class="reminder-item">
                    <i class="fas fa-calendar-check"></i>
                    <div class="reminder-info">
                        <div class="reminder-title">今日挂号提醒</div>
                        <div class="reminder-detail">心内科 李医生 下午 14:30</div>
                    </div>
                </div>
            </div>
        </div> -->

        <!-- 近期就诊 -->
        <div class="recent-visits">
            <div class="section-title">近期预约记录</div>
            <div class="visits-list">
                <div v-for="(visit, index) in haspayList" :key="index" class="visit-item">
                    <div class="visit-date">{{ visit.date }}</div>
                    <div class="visit-info">
                        <div class="visit-department">{{ visit.orderNumber }}</div>
                        <div class="visit-doctor">{{ visit.patientName }}</div>
                    </div>
                    <div class="visit-status">待会诊</div>
                </div>
            </div>
        </div>

        <!-- 已取消订单 -->
        <div class="recent-visits">
            <div class="section-title">已取消订单</div>
            <div class="visits-list">
                <div v-for="(visit, index) in cancelist" :key="index" class="visit-item">
                    <div class="visit-date">{{ visit.date }}</div>
                    <div class="visit-info">
                        <div class="visit-department">{{ visit.orderNumber }}</div>
                        <div class="visit-doctor">{{ visit.patientName }}医生 预约时间{{ visit.timeSolt }}</div>
                    </div>
                    <div>
                        <!-- 创建日期 {{ formatDate(visit.createTime) }} -->
                    </div>

                    <div class="visit-status">已取消</div>
                </div>
            </div>
        </div>
        <!-- 健康资讯 -->
        <div class="health-news">
            <h2>健康资讯</h2>
            <div class="news-list">
                <div v-for="(news, index) in healthNews" :key="index" class="news-item">
                    <img :src="news.image">
                    <div class="news-content">
                        <h3>{{ news.title }}</h3>
                        <p>{{ news.description }}</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 支付确认弹窗 -->
        <div class="modal" v-if="showPaymentModal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>确认支付</h3>
                    <button class="close-btn" @click="showPaymentModal = false">&times;</button>
                </div>
                <div class="modal-body">
                    <p>订单编号：{{ selectedOrder.orderNumber }}</p>
                    <p>医生：{{ selectedOrder.patientName }}</p>
                    <p>预约日期：{{ selectedOrder.date }} {{ selectedOrder.timeSlot }}</p>
                    <p class="amount">支付金额：¥{{ selectedOrder.totalAmount }}</p>
                </div>
                <div class="modal-footer">
                    <button class="cancel-btn" @click="showPaymentModal = false">取消</button>
                    <button class="confirm-pay-btn" @click="confirmPayment">确认支付</button>
                </div>
            </div>
        </div>

        <!-- 支付成功提示 -->
        <div class="toast" v-if="showSuccessToast">
            <i class="fas fa-check-circle"></i>
            <span>支付成功！</span>
        </div>

        <!-- 自定义加载弹窗 -->
        <div class="loading-modal" v-if="showLoading">
            <div class="loading-content">
                <div class="spinner"></div>
                <div class="loading-text">{{ loadingText }}</div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import router from '@/router';
import { ref, computed, onMounted } from 'vue';
import { selectByuserIdForUnpay, selectAppByOrCond1 } from "@/api/healthcare"
import { alipayOrder } from "@/api/healthcare"
import { ElMessage } from 'element-plus';

// 状态管理
const showPaymentDetails = ref(false);
const showPaymentModal = ref(false);
const showSuccessToast = ref(false);
const selectedOrder = ref(null);
const unpayList = ref([]);
let haspayList = ref([]);
let cancelist = ref([]);
let user = {};
// 新增加载状态
const showLoading = ref(false);
const loadingText = ref('正在处理...');

// 健康资讯数据
const healthNews = [
    {
        title: '冬季养生保健指南',
        description: '专家建议：适度运动、均衡饮食、保暖防寒是冬季养生的关键。',
        image: 'https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/f987ca7e72153bc70a47ac9ccd2ce57e.jpg'
    },
    {
        title: '高血压患者饮食注意事项',
        description: '控制盐分摄入、规律作息、定期监测血压对于高血压患者至关重要。',
        image: 'https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/4bdbce6d0577540c204614c87cf1f821.jpg'
    },
    {
        title: '老年人防跌倒指南',
        description: '居家环境改造、适当运动、营养补充可有效预防老年人跌倒。',
        image: 'https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/f987ca7e72153bc70a47ac9ccd2ce57e.jpg'
    }
];

// 近期就诊记录
const recentVisits = [
    {
        date: '2024-01-15',
        department: '心内科',
        doctor: '李医生',
        status: '已完成'
    },
    {
        date: '2024-01-10',
        department: '骨科',
        doctor: '王医生',
        status: '已完成'
    },
    {
        date: '2024-01-05',
        department: '内分泌科',
        doctor: '张医生',
        status: '已完成'
    }
];

// 计算总待支付金额

// 切换支付详情显示/隐藏
const togglePaymentDetails = () => {
    showPaymentDetails.value = !showPaymentDetails.value;
};

// 处理支付
const handlePayment = (order) => {
    selectedOrder.value = order;
    showPaymentModal.value = true;
};
// 自定义格式输出
function formatDate(dates) {
    let date = new Date(dates)
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 输出: "2025-07-23 09:47:40"（北京时间）
// 确认支付
const confirmPayment = async () => {
    // 显示加载弹窗
    showLoading.value = true;
    loadingText.value = '正在跳转至支付宝...';

    try {
        const paramsOrder = {
            TradeNo: selectedOrder.value.orderNumber,
            totalAmount: selectedOrder.value.totalAmount,
            subject: "预约订单",
            scheduleId: "---",
            patientId: user.userId,
            doctorId: "",
            appointmentDate: "",
            paymentAmount: selectedOrder.value.paymentAmount,
            timeSolt: selectedOrder.value.timeSlot,
            userId: user.userId,
            payType: 1,
            paymentType: 1,
            status: 1,
            patientName: selectedOrder.value.name,
            idCard: user.idCard,
            date: selectedOrder.value.date
        };

        const alipayRes = await alipayOrder(paramsOrder, { custom: { showLoading: false } });

        const div = document.createElement('div');
        div.innerHTML = alipayRes.data;
        document.body.appendChild(div);

        // 自动提交表单
        const form = div.querySelector('form');
        if (form) {
            form.submit();
        } else {
            ElMessage.error('支付表单生成失败');
            showLoading.value = false; // 隐藏加载
        }

        // 关闭支付弹窗
        showPaymentModal.value = false;
    } catch (error) {
        ElMessage.error('支付请求失败，请稍后重试');
        console.error('支付错误:', error);
        showLoading.value = false; // 隐藏加载
    }
};

// 获取待支付订单
const getUnpay = (data) => {
    // 显示加载
    showLoading.value = true;
    loadingText.value = '正在加载订单数据...';

    selectAppByOrCond1(data, { custom: { showLoading: false } })
        .then(res => {
            console.log("res", res.data);
            if (res.code == 200) {
                unpayList.value = res.data;
            }
        })
        .finally(() => {
            // 隐藏加载
            showLoading.value = false;
        });
};
// 获取待支付订单
const gethaspay = (data) => {
    // 显示加载
    // showLoading.value = true;
    // loadingText.value = '正在加载订单数据...';

    selectByuserIdForUnpay(data, { custom: { showLoading: false } })
        .then(res => {
            console.log("res", res.data);
            if (res.code == 200) {
                haspayList.value = res.data;
            }
        })
        .finally(() => {
            // 隐藏加载
            showLoading.value = false;
        });
};
// 获取已经取消的订单
const getcancelist = (data) => {
    // 显示加载
    // showLoading.value = true;
    // loadingText.value = '正在加载订单数据...';
    selectByuserIdForUnpay(data, { custom: { showLoading: false } })
        .then(res => {
            console.log("res", res.data);
            if (res.code == 200) {
                cancelist.value = res.data;
            }
        })
        .finally(() => {
            // 隐藏加载
            showLoading.value = false;
        });
};


onMounted(() => {
    user = JSON.parse(localStorage.getItem("user") || '{}');
    let data = {
        userId: user.userId, status: 1, pay_type: 1
    }
    //未支付的
    getUnpay(data);
    data.status = 2;
    //已经支付
    gethaspay(data);
    data.status = 4;
    //已经取消订单
    getcancelist(data);
});
</script>

<style scoped>
/* 基础样式 */
.app-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    font-family: 'Arial', sans-serif;
    color: #333;
}

.section-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #2d3748;
    display: flex;
    align-items: center;
}

/* 健康提醒 */
.health-reminder {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.reminder-content {
    display: flex;
    gap: 15px;
}

.reminder-item {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 15px;
    background-color: #f8fafc;
    border-radius: 8px;
    transition: transform 0.2s, box-shadow 0.2s;
}

.reminder-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.reminder-item i {
    font-size: 24px;
    color: #2c5282;
}

.reminder-title {
    font-weight: bold;
    margin-bottom: 5px;
}

.reminder-detail {
    color: #64748b;
    font-size: 14px;
}

/* 待支付提醒 */
.payment-reminder {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    border-left: 4px solid #f56565;
}

.payment-title {
    cursor: pointer;
    justify-content: space-between;
}

.amount-badge {
    background-color: #f56565;
    color: white;
    padding: 3px 10px;
    border-radius: 12px;
    font-size: 14px;
    font-weight: normal;
}

.toggle-icon {
    transition: transform 0.3s ease;
    margin-left: 10px;
}

.rotated {
    transform: rotate(180deg);
}

.payment-details {
    margin-top: 15px;
    overflow: hidden;
    transition: max-height 0.3s ease;
}

.payment-list {
    border-top: 1px solid #eee;
    padding-top: 15px;
}

.payment-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f1f1f1;
}

.payment-item:last-child {
    border-bottom: none;
}

.payment-info {
    flex: 1;
}

.payment-info .payment-title {
    font-weight: bold;
    margin-bottom: 5px;
    font-size: 15px;
}

.payment-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    margin-bottom: 5px;
    font-size: 14px;
    color: #666;
}

.payment-amount {
    color: #f56565;
    font-weight: bold;
}

.pay-button {
    background-color: #f56565;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.2s;
}

.pay-button:hover {
    background-color: #e53e3e;
}

/* 近期就诊 */
.recent-visits {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.visits-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.visit-item {
    display: flex;
    align-items: center;
    padding: 15px;
    background-color: #f8fafc;
    border-radius: 8px;
}

.visit-date {
    width: 100px;
    font-weight: bold;
}

.visit-info {
    flex: 1;
    margin-left: 20px;
}

.visit-department {
    font-weight: bold;
    margin-bottom: 3px;
}

.visit-doctor {
    color: #64748b;
    font-size: 14px;
}

.visit-status {
    padding: 5px 12px;
    background-color: #e6fffa;
    color: #319795;
    border-radius: 20px;
    font-size: 14px;
}

/* 健康资讯 */
.health-news {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.health-news h2 {
    font-size: 18px;
    margin-bottom: 15px;
    color: #2d3748;
}

.news-list {
    display: flex;
    gap: 20px;
}

.news-item {
    flex: 1;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: transform 0.2s;
}

.news-item:hover {
    transform: translateY(-3px);
}

.news-item img {
    width: 100%;
    height: 160px;
    object-fit: cover;
}

.news-content {
    padding: 15px;
}

.news-content h3 {
    font-size: 16px;
    margin-bottom: 8px;
}

.news-content p {
    font-size: 14px;
    color: #64748b;
    line-height: 1.5;
}

/* 支付弹窗 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background-color: white;
    border-radius: 8px;
    width: 90%;
    max-width: 400px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
    padding: 15px 20px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h3 {
    margin: 0;
    font-size: 18px;
}

.close-btn {
    background: none;
    border: none;
    font-size: 20px;
    cursor: pointer;
    color: #666;
}

.modal-body {
    padding: 20px;
}

.modal-body p {
    margin: 10px 0;
}

.modal-body .amount {
    font-size: 18px;
    color: #f56565;
    font-weight: bold;
    margin-top: 20px;
}

.modal-footer {
    padding: 15px 20px;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.cancel-btn {
    padding: 8px 16px;
    border: 1px solid #ddd;
    background-color: white;
    border-radius: 4px;
    cursor: pointer;
}

.confirm-pay-btn {
    padding: 8px 16px;
    background-color: #f56565;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

/* 支付成功提示 */
.toast {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    background-color: #48bb78;
    color: white;
    padding: 12px 20px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 8px;
    z-index: 1001;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    animation: fadein 0.5s, fadeout 0.5s 2.5s;
}

.toast i {
    font-size: 18px;
}

/* 自定义加载弹窗 */
.loading-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2000;
}

.loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* 加载动画 */
.spinner {
    width: 50px;
    height: 50px;
    border: 5px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 1s ease-in-out infinite;
    margin-bottom: 15px;
}

.loading-text {
    color: white;
    font-size: 16px;
    text-align: center;
}

/* 动画 */
@keyframes fadein {
    from {
        bottom: 0;
        opacity: 0;
    }

    to {
        bottom: 20px;
        opacity: 1;
    }
}

@keyframes fadeout {
    from {
        bottom: 20px;
        opacity: 1;
    }

    to {
        bottom: 0;
        opacity: 0;
    }
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* 响应式调整 */
@media (max-width: 768px) {

    .reminder-content,
    .news-list {
        flex-direction: column;
    }

    .payment-meta {
        flex-direction: column;
        gap: 5px;
    }
}
</style>